package org.example.controller.currency;

import cn.hutool.core.thread.ThreadUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.example.common.JsonResult;
import org.example.controller.rep.CurrencyGroupRep;
import org.example.controller.rep.CurrencyRateDetailRep;
import org.example.controller.req.CurrencyHistoryReq;
import org.example.controller.req.CurrencyRateReq;
import org.example.dao.currency.CurrencyExchangeRateDao;
import org.example.dao.currency.CurrencyMsgDao;
import org.example.entity.currency.CurrencyExchangeRateEntity;
import org.example.entity.currency.CurrencyMsgEntity;
import org.example.service.currency.CurrencyService;
import org.example.service.utils.Constant;
import org.example.service.utils.IConst;
import org.example.service.utils.okhttp.OkHttpClients;
import org.example.service.utils.okhttp.OkHttpParam;
import org.example.service.utils.okhttp.OkhttpResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Value;


import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

import static org.example.service.utils.IConst.API_BASE;

/**
 * @Author tql
 * @Desc 货币汇率 控制器
 * @Date 2024/2/26 14:36
 * @Version 1.0
 */
@Slf4j
@RestController
@RequestMapping(API_BASE + "currency")
@Api(tags = IConst.MODULE_CURRENCY_RATE)
public class CurrencyRateController {



    @Resource
    private CurrencyService currencyService;

    @Resource
    private CurrencyMsgDao currencyMsgDao;

    @Resource
    private CurrencyExchangeRateDao currencyExchangeRateDao;

    @GetMapping("/sync")
    @ApiOperation(value = "货币汇率同步", tags = IConst.MODULE_CURRENCY_RATE)
    public JsonResult<Boolean> sync() {
        OkHttpParam param = new OkHttpParam();
        String api = "https://api.exchangerate-api.com/v4/latest/";
        List<CurrencyMsgEntity> currencyMsgEntities = currencyMsgDao.selectList(null);
        currencyMsgEntities.forEach(obj -> {
            String string = api + obj.getCurrencyEn();
            OkhttpResult<String> result = null;
            param.setApiUrl(string);
            try {
                result = OkHttpClients.get(param, String.class);
                String apiRes = result.getResult();
                currencyService.syncCurrencyRate(apiRes);
                ThreadUtil.safeSleep(3000);
            } catch (Exception e) {
                log.info("[失败]api:{},返回值:{}", api, result);
                e.printStackTrace();
            }
        });
        return JsonResult.ok(true);
    }

    @GetMapping("/list")
    @ApiOperation(value = "货币信息列表", tags = IConst.MODULE_CURRENCY_RATE)
    public JsonResult<List<CurrencyMsgEntity>> list() {
        List<CurrencyMsgEntity> currencyMsgEntities = currencyMsgDao.selectList(new QueryWrapper<CurrencyMsgEntity>()
                .eq("is_often_used", Constant.ONE));
        currencyMsgEntities = currencyMsgEntities.stream().sorted(Comparator.comparing(CurrencyMsgEntity::getSequence, Comparator.nullsLast(Integer::compareTo))).collect(Collectors.toList());
        return JsonResult.ok(currencyMsgEntities);
    }

    @GetMapping("/hot/list")
    @ApiOperation(value = "热门货币信息列表", tags = IConst.MODULE_CURRENCY_RATE)
    public JsonResult<List<CurrencyMsgEntity>> hotList() {
        List<CurrencyMsgEntity> currencyMsgEntities = currencyMsgDao.selectList(new QueryWrapper<CurrencyMsgEntity>()
                .eq("is_often_used", Constant.ONE)
                .isNotNull("sequence"));
        currencyMsgEntities = currencyMsgEntities.stream().sorted(Comparator.comparing(CurrencyMsgEntity::getSequence, Comparator.nullsLast(Integer::compareTo))).collect(Collectors.toList());
        return JsonResult.ok(currencyMsgEntities);
    }


    @PostMapping("/history/list")
    @ApiOperation(value = "货币历史汇率列表", tags = IConst.MODULE_CURRENCY_RATE)
    public JsonResult<Object> historyList(@RequestBody CurrencyHistoryReq currencyHistoryReq) {
        Object lists = currencyService.history(currencyHistoryReq);
        return JsonResult.ok(lists);
    }

    @GetMapping("/group/list")
    @ApiOperation(value = "货币信息分组列表", tags = IConst.MODULE_CURRENCY_RATE)
    public JsonResult<Map<String, List<CurrencyGroupRep>>> groupList() {
        List<CurrencyMsgEntity> currencyMsgEntities = currencyMsgDao.selectList(new QueryWrapper<CurrencyMsgEntity>()
                .eq("is_often_used", Constant.ONE));

        List<CurrencyGroupRep> lists = new ArrayList<>();
        currencyMsgEntities.forEach(obj -> {
            CurrencyGroupRep build = CurrencyGroupRep.builder()
                    .currencyIcon(obj.getCurrencyIcon())
                    .currencyZn(obj.getCurrencyZn())
                    .currencyEn(obj.getCurrencyEn())
                    .sequence(obj.getSequence())
                    // 首字母
                    .letter(obj.getCurrencyEn().substring(0, 1)).build();
            lists.add(build);

        });

        Map<String, List<CurrencyGroupRep>> map = lists.stream().collect(
                Collectors.groupingBy(CurrencyGroupRep::getLetter));
        // stream分组排序
//        Map<String, List<CurrencyGroupRep>> map = lists.stream().collect(
//                Collectors.groupingBy(CurrencyGroupRep::getLetter, HashMap::new,
//                        Collectors.collectingAndThen(Collectors.toList(),
//                                //正序
//                                list -> lists.stream().sorted(Comparator.comparing(CurrencyGroupRep::getSequence, Comparator.nullsLast(Integer::compareTo)))
//
//                                        .collect(Collectors.toList())
//                        )));
        return JsonResult.ok(map);
    }

    @PostMapping("/rate")
    @ApiOperation(value = "货币汇率查询", tags = IConst.MODULE_CURRENCY_RATE)
    public JsonResult<CurrencyRateDetailRep> rate(@RequestBody CurrencyRateReq currencyRateReq) {
        CurrencyExchangeRateEntity currencyExchangeRateEntities = currencyExchangeRateDao.selectOne(
                new QueryWrapper<CurrencyExchangeRateEntity>()
                        .eq("currency_master_en", currencyRateReq.getCurrencyMasterEn())
                        .eq("currency_slave_en", currencyRateReq.getCurrencySlaveEn())
        );
        CurrencyRateDetailRep build = CurrencyRateDetailRep.builder().exchangeRate(
                Optional.ofNullable(currencyExchangeRateEntities).map(CurrencyExchangeRateEntity::getMasterExchangeRate).orElse(null)).build();
        return JsonResult.ok(build);
    }
}
